package app;

import cas.client.User;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

@WebListener()
public class OnlineUserListener implements HttpSessionListener, HttpSessionAttributeListener {
    public static final Map<String, User> ONLINE_USERS = new HashMap<>();

    public OnlineUserListener() {}

    @Override
    public void sessionCreated(HttpSessionEvent se) {}

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        // 用户下线
        User user = (User) se.getSession().getAttribute("user");
        if (user != null) {
            ONLINE_USERS.remove(user.getAccount());
        }
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        if (sbe.getName().equals("user")) {
            // 用户上线
            User user = (User) sbe.getValue();
            if (user != null) {
                user.setLoginTimestamp(Timestamp.from(Instant.now()));
                ONLINE_USERS.put(user.getAccount(), user);
            }
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        if (sbe.getName().equals("user")) {
            // 用户下线
            User user = (User) sbe.getValue();
            if (user != null) {
                ONLINE_USERS.remove(user.getAccount());
            }
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {}
}
